package com.sykj.cloud.system.service.impl;

import com.sykj.cloud.common.core.constant.UserConstants;
import com.sykj.cloud.common.core.exception.CustomException;
import com.sykj.cloud.common.core.utils.DateUtils;
import com.sykj.cloud.common.core.utils.IdUtils;
import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.system.api.domain.OrgDept;
import com.sykj.cloud.system.api.domain.SysRole;
import com.sykj.cloud.system.domain.vo.TreeSelect;
import com.sykj.cloud.system.mapper.OrgDeptMapper;
import com.sykj.cloud.system.mapper.SysRoleMapper;
import com.sykj.cloud.system.service.IOrgDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 组织部门Service业务层处理
 *
 * @author mr.will
 * @date 2021-03-15
 */
@Service
public class OrgDeptServiceImpl implements IOrgDeptService
{
    @Autowired
    private OrgDeptMapper orgDeptMapper;
    @Autowired
    SysRoleMapper sysRoleMapper;

    /**
     * 新增组织部门
     *
     * @param orgDept 组织部门
     * @return 结果
     */
    @Override
    public int insertOrgDept(OrgDept orgDept)
    {
        OrgDept info = orgDeptMapper.getOrgDeptById(orgDept.getParentId());
        if(info!=null)
        {
            // 如果父节点的状态不正常,不允许新增子节点
            if (UserConstants.DEPT_NORMAL==info.getValid())
            {
                throw new CustomException("部门停用，不允许新增子节点");
            }
            if(StringUtils.isNotBlank(info.getAncestors()))
            {
                orgDept.setAncestors(info.getAncestors() + "," + orgDept.getParentId());
            }else
            {
                orgDept.setAncestors(orgDept.getParentId());
            }
        }
        orgDept.setGuid(IdUtils.fastSimpleUUID());
        orgDept.setCreateTime(DateUtils.getNowDate());
        return orgDeptMapper.insertOrgDept(orgDept);
    }

    /**
     * 修改组织部门
     *
     * @param orgDept 组织部门
     * @return 结果
     */
    @Override
    public int updateOrgDept(OrgDept orgDept)
    {
        // 新上级
        OrgDept newParentDept = orgDeptMapper.getOrgDeptById(orgDept.getParentId());
        // 旧的数据
        OrgDept oldDept = orgDeptMapper.getOrgDeptById(orgDept.getGuid());
        orgDept.setUpdateTime(DateUtils.getNowDate());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = null;
            if(newParentDept.getAncestors()!=null){
                newAncestors =  newParentDept.getAncestors() + "," + newParentDept.getGuid();
            }else {
                newAncestors = newParentDept.getGuid();
            }
            String oldAncestors = oldDept.getAncestors();
            orgDept.setAncestors(newAncestors);
            updateDeptChildren(orgDept.getGuid(), newAncestors, oldAncestors);
        }

        int result = orgDeptMapper.updateOrgDept(orgDept);
//        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
//        {
//            // 如果该部门是启用状态，则启用该部门的所有上级部门
//            updateParentDeptStatus(dept);
//        }
        return result;



    }



    /**
     * 修改子元素关系
     *
     * @param guid 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(String guid, String newAncestors, String oldAncestors)
    {
        List<OrgDept> children = orgDeptMapper.listChildrenDeptsById(guid);
        for (OrgDept child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            orgDeptMapper.updateDeptChildren(children);
        }
    }


    /**
     * 批量删除组织部门
     *
     * @param guids 需要删除的组织部门ID
     * @return 结果
     */
    @Override
    public int deleteOrgDeptByIds(String[] guids)
    {
        return orgDeptMapper.deleteOrgDeptByIds(guids);
    }

    /**
     * 删除组织部门信息
     *
     * @param guid 组织部门ID
     * @return 结果
     */
    @Override
    public int deleteOrgDeptById(String guid)
    {
        return orgDeptMapper.deleteOrgDeptById(guid);
    }



    /**
     * 查询组织部门
     *
     * @param guid 组织部门ID
     * @return 组织部门
     */
    @Override
    public OrgDept getOrgDeptById(String guid)
    {
        return orgDeptMapper.getOrgDeptById(guid);
    }

    /**
     * 查询组织部门列表
     *
     * @param orgDept 组织部门
     * @return 组织部门
     */
    @Override
    public List<OrgDept> listOrgDepts(OrgDept orgDept)
    {
        return orgDeptMapper.listOrgDepts(orgDept);
    }

    @Override
    public List<OrgDept> buildDeptTree(List<OrgDept> depts)
    {
        List<OrgDept> returnList = new ArrayList<OrgDept>();
        List<String> tempList = new ArrayList<String>();
        for (OrgDept dept : depts)
        {
            tempList.add(dept.getGuid());
        }
        for (Iterator<OrgDept> iterator = depts.iterator();
             iterator.hasNext();)
        {
            OrgDept dept = (OrgDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<OrgDept> depts) {
        List<OrgDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<String> listDeptsByRoleId(String roleId) {
        SysRole role = sysRoleMapper.getSysRoleById(roleId);
        return orgDeptMapper.listDeptsByRoleId(roleId, role.isDeptCheckStrictly());
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return 0;
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return false;
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return false;
    }

    @Override
    public String checkDeptNameUnique(OrgDept dept) {
        return null;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<OrgDept> list, OrgDept t)
    {
        // 得到子节点列表
        List<OrgDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (OrgDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<OrgDept> getChildList(List<OrgDept> list, OrgDept t)
    {
        List<OrgDept> tlist = new ArrayList<OrgDept>();
        Iterator<OrgDept> it = list.iterator();
        while (it.hasNext())
        {
            OrgDept n = (OrgDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getGuid()))
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<OrgDept> list, OrgDept t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
